package com.ynet.middleground.user.model;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.user.bean.DeleteEnterpriseUserRoleInfoReq;
import com.ynet.middleground.user.bean.EnterpriseUserRoleInfoReq;
import com.ynet.middleground.user.bean.QueryEnterpriseUserRoleListReq;
import com.ynet.middleground.user.bean.UpdateEnterpriseUserRoleInfoReq;
import com.ynet.middleground.user.common.ErrorMessageConstant;
import com.ynet.middleground.user.common.SystemConstant;
import com.ynet.middleground.user.dao.EnterpriseUserRoleMapper;
import com.ynet.middleground.user.dao.UserBaseInformationMapper;
import com.ynet.middleground.user.dao.UserRoleRelationMapper;
import com.ynet.middleground.user.dto.EnterpriseUserRoleDto;
import com.ynet.middleground.user.entity.EnterpriseUserRole;
import com.ynet.middleground.user.entity.UserBaseInformation;
import com.ynet.middleground.user.entity.UserRoleRelation;
import org.apache.commons.lang.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 企业员工用户角色管理 服务实现类
 * </p>
 *
 * @author Wangxz
 * @since 2019-10-25
 */
@Component
public class EnterpriseUserRoleModel extends ServiceImpl<EnterpriseUserRoleMapper, EnterpriseUserRole> {

    @Autowired
    Mapper mapper;

    // 角色关系
    @Autowired
    UserRoleRelationMapper userRoleRelationMapper;

    //用户基础信息
    @Autowired
    UserBaseInformationMapper userBaseInformationMapper;

    private QueryWrapper<EnterpriseUserRole> queryWrapper = null;

    /**
     * 企业用户添加角色
     *
     * @param requestObject
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer addEnterpriseUserRoleModel(EnterpriseUserRoleInfoReq requestObject) throws BusinessException {
        if (checkRepeatRole(requestObject.getRoleName(), requestObject.getLevelCode())) {
            throw new BusinessException("当前等级已存在该角色名，请重新输入！", ErrorMessageConstant.ECUC0027_CODE);
        }
//        if (queryUser(requestObject.getOperationUserId(),requestObject.getChannel())){
//            throw new BusinessException("当前操作员非企业用户", ErrorMessageConstant.ECUC0027_CODE);
//        }
        // 验证通过，添加角色
        EnterpriseUserRole enterpriseUserRole = mapper.map(requestObject, EnterpriseUserRole.class);
        //保存信息
        enterpriseUserRole.setCreateBy(requestObject.getOperationUserId());
        enterpriseUserRole.setGmtCreate(LocalDateTime.now());
        enterpriseUserRole.setBusinessSeqNo(requestObject.getTraceId());
        enterpriseUserRole.setEntOperatorNo(requestObject.getOperationUserId());
        boolean save = this.save(enterpriseUserRole);
        if (!save) {
            throw new BusinessException("角色信息添加失败", ErrorMessageConstant.ECUC0027_CODE);
        }
        return enterpriseUserRole.getRoleId();
    }

    /**
     * 分页查询角色信息
     *
     * @param requestObj
     * @return
     * @throws Exception
     */
    public List<EnterpriseUserRoleDto> queryEnterpriseUserRoleList(QueryEnterpriseUserRoleListReq requestObj)
        throws Exception {
        // 获取分页信息
        PagerInfo pagerInfo = requestObj.getPagerInfo();
        // 获取总条数
        pagerInfo.setTotal(this.count());
        String sortField = requestObj.getSortField();
        String sortOrder = requestObj.getSortOrder();
        queryWrapper = new QueryWrapper<>();
        if (null != requestObj.getRoleId()){
            queryWrapper.eq("role_id", requestObj.getRoleId());
        }
        if (null != requestObj.getRoleName()){
            queryWrapper.like("role_name", requestObj.getRoleName());
        }
        if (null != requestObj.getLevelCode()){
            queryWrapper.eq("level_code", requestObj.getLevelCode());
        }
        // 2021-01-26 支持自定义排序查询 songyf
        if (StringUtils.isNotEmpty(sortField)&&StringUtils.isNotEmpty(sortOrder)) {
            if("createTime".equals(sortField)) {
                if("asc".equals(sortOrder)) {
                    queryWrapper.orderByAsc("gmt_create");
                }else if("desc".equals(sortOrder)) {
                    queryWrapper.orderByDesc("gmt_create");
                }
            }else if("roleName".equals(sortField)) {
                if("asc".equals(sortOrder)) {
                    queryWrapper.orderByAsc("role_name");
                }else if("desc".equals(sortOrder)) {
                    queryWrapper.orderByDesc("role_name");
                }
            }else if("levelCode".equals(sortField)) {
                if("asc".equals(sortOrder)) {
                    queryWrapper.orderByAsc("level_code");
                }else if("desc".equals(sortOrder)) {
                    queryWrapper.orderByDesc("level_code");
                }
            }
        }else if(StringUtils.isEmpty(sortField)&&StringUtils.isEmpty(sortOrder)) {
        }else {
            throw new BusinessException(ErrorMessageConstant.ECUC0059_MESSAGE, ErrorMessageConstant.ECUC0059_CODE);
        }
        // 分页查询用户角色
        IPage<EnterpriseUserRole> userRoleIPage = this.page(new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize()), queryWrapper);
        List<EnterpriseUserRole> userRoleIPageRecords = userRoleIPage.getRecords();
        List<EnterpriseUserRoleDto> enterpriseUserRoleList = new ArrayList<>();
        // 查询结果是否为空
        if (null == userRoleIPageRecords) {
            return enterpriseUserRoleList;
        }
        enterpriseUserRoleList = userRoleIPageRecords.stream().map(x -> mapper.map(x, EnterpriseUserRoleDto.class))
            .collect(Collectors.toList());
        // 返回总条数
        requestObj.setPagerInfo(pagerInfo);
        return enterpriseUserRoleList;
    }

    /**
     * 更新角色信息
     *
     * @param requestObj
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public String updateEnterpriseUserRole(UpdateEnterpriseUserRoleInfoReq requestObj) throws BusinessException {
        // add by gaole.dai 2019-12-17 修改更新角色信息不存在角色或校验和渠道覆盖问题 begin
        Integer roleId = requestObj.getRoleId();
        String roleName = requestObj.getRoleName();
        Integer levelCode = requestObj.getLevelCode();
        QueryWrapper<EnterpriseUserRole> queryWrapperEur = new QueryWrapper<>();
        EnterpriseUserRole enterpriseUserRole = this.getById(requestObj.getRoleId());
        if (enterpriseUserRole == null) {
            throw new BusinessException("角色(" + roleId + ")不存在", ErrorMessageConstant.ECUC0027_CODE);
        }
        if (StringUtils.isNotEmpty(roleName) && levelCode != null) {
            queryWrapperEur.eq("role_name", roleName);
            queryWrapperEur.eq("level_code", levelCode);
            queryWrapperEur.ne("role_id", roleId);
            Integer integer = this.getBaseMapper().selectCount(queryWrapperEur);
            if (integer > 0) {
                throw new BusinessException("角色名称和层级关系重复", ErrorMessageConstant.ECUC0027_CODE);
            }
        }
        if (StringUtils.isNotEmpty(roleName)) {
            queryWrapperEur = new QueryWrapper<>();
            queryWrapperEur.eq("role_name", roleName);
            queryWrapperEur.eq("level_code", enterpriseUserRole.getLevelCode());
            queryWrapperEur.ne("role_id", roleId);
            Integer integer = this.getBaseMapper().selectCount(queryWrapperEur);
            if (integer > 0) {
                throw new BusinessException("角色名称和层级关系重复", ErrorMessageConstant.ECUC0027_CODE);
            }
        }

        if (levelCode != null) {
            queryWrapperEur = new QueryWrapper<>();
            queryWrapperEur.eq("role_name", enterpriseUserRole.getRoleName());
            queryWrapperEur.eq("level_code", levelCode);
            queryWrapperEur.ne("role_id", roleId);
            Integer integer = this.getBaseMapper().selectCount(queryWrapperEur);
            if (integer > 0) {
                throw new BusinessException("层级关系重复", ErrorMessageConstant.ECUC0027_CODE);
            }
        }

        String tempChannel = enterpriseUserRole.getChannel();
        mapper.map(requestObj, enterpriseUserRole);
        enterpriseUserRole.setChannel(tempChannel);
        enterpriseUserRole.setGmtModified(LocalDateTime.now());
        enterpriseUserRole.setModifiedBy(requestObj.getOperationUserId());
        this.updateById(enterpriseUserRole);
        return SystemConstant.SYSTEM_SUCCESS;
        // add by gaole.dai 2019-12-17 修改更新角色信息不存在角色或校验和渠道覆盖问题 end
    }

    /**
     * 删除角色信息
     *
     * @param requestObj
     * @throws BusinessException
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteEnterpriseUserRole(DeleteEnterpriseUserRoleInfoReq requestObj) throws BusinessException {
        // 验证角色是否存在
        EnterpriseUserRole enterpriseUserRole = this.getById(requestObj.getRoleId());
        if (enterpriseUserRole == null) {
            throw new BusinessException("角色(" + requestObj.getRoleId() + ")不存在", ErrorMessageConstant.ECUC0027_CODE);
        }
        // 验证角色下是否有下挂员工
        if (queryUserRoleRelationMapper(requestObj.getRoleId())){
            throw new BusinessException("该角色下有下挂员工，无法删除", ErrorMessageConstant.ECUC0027_CODE);
        }
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", requestObj.getRoleId());
        boolean remove = this.remove(queryWrapper);
        if (!remove) {
            throw new BusinessException("角色信息删除失败", ErrorMessageConstant.ECUC0027_CODE);
        }
    }

    /**
     * 验证该角色在这一级别是否唯一
     * 
     * @param roleName,levelCode
     * @return boolean
     */
    public boolean checkRepeatRole(String roleName, Integer levelCode) {
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_name", roleName);
        queryWrapper.eq("level_code", levelCode);
        int count = this.count(queryWrapper);
        return count != 0;
    }

    /**
     * 验证企业用户真实性
     *
     * @param userId
     * @param channel
     * @return
     */
    public boolean queryUser(Integer userId ,String channel){
        QueryWrapper<UserBaseInformation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("user_type", SystemConstant.USER_TYPE_0);
        return userBaseInformationMapper.selectCount(queryWrapper) != 1;
    }

    /**
     * 验证角色下是否下挂有用户
     *
     * @param roleId
     * @return
     */
    public boolean queryUserRoleRelationMapper(Integer roleId){
        QueryWrapper<UserRoleRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        return userRoleRelationMapper.selectCount(queryWrapper) != 0;
    }
}
